package com.example.warehousems.component;

import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.warehousems.config.Constants;
import com.example.warehousems.util.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.HashMap;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(JwtToken.TOKEN_HEADER);
        String msg;
        ServletOutputStream os = response.getOutputStream();
        String uri = request.getRequestURI();

        try {
            JwtToken.verify(token);
            log.info("in token interceptor, this url is {}, valid", uri);
            return true;
        } catch (TokenExpiredException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            msg = "token is expired";
            log.error("in token interceptor, this url is {}, expired", uri);
            os.write(JSON.toJSONString(BaseResponse.error(msg)).getBytes());
//            String refreshToken = JwtToken.extractRefreshToken(token);
//            // 解码 Refresh Token
//            DecodedJWT decodedRefreshToken = JWT.require(Algorithm.HMAC256(Constants.REFRESH_TOKEN_SECRET)).build().verify(refreshToken);
//
//            // 校验 Refresh Token 是否有效
//            if (decodedRefreshToken.getExpiresAt().before(new Date())) {
//                msg = "refresh token is expired";
//                log.error("in token interceptor, this url is {}, expired", uri);
//                os.write(JSON.toJSONString(BaseResponse.error(msg)).getBytes());
//            } else {
//                // 从 Refresh Token 中获取用户信息
//                String id = decodedRefreshToken.getClaim("id").asString();
//                String username = decodedRefreshToken.getClaim("username").asString();
//                String email = decodedRefreshToken.getClaim("email").asString();
//                String role = decodedRefreshToken.getClaim("role").asString();
//
//                // 根据 Refresh Token 中的信息生成新的 Access Token
//                HashMap<String, String> claims = new HashMap<>();
//                claims.put("id", id);
//                claims.put("username", username);
//                claims.put("email", email);
//                claims.put("role", role);
//                String newAccessToken = JwtToken.create(claims);
//                response.setHeader("Authorization", "Bearer " + newAccessToken);
//            }
        } catch (SignatureVerificationException e) {
            msg = "signature is invalid";
            log.error("in token interceptor, this url is {}, invalid signature", uri);
            os.write(JSON.toJSONString(BaseResponse.error(msg)).getBytes());
        } catch (AlgorithmMismatchException e) {
            msg = "wrong encrypt algorithm";
            log.error("in token interceptor, this url is {}, wrong encrypt algorithm", uri);
            os.write(JSON.toJSONString(BaseResponse.error(msg)).getBytes());
        } catch (Exception e) {
            msg = "invalid token";
            log.error(token);
            log.error("in token interceptor, this url is {}, invalid token", uri);
            log.error(e.toString());
            os.write(JSON.toJSONString(BaseResponse.error(msg)).getBytes());
        }
        return false;
    }
}
